﻿using PersistentObject.Common;
using PersistentObject.Common.Criteria;
using PersistentObject.Common.Exceptions;
using PersistentObject.Common.Schema;
using PersistentObject.Common.Sorts;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;


namespace PersistentObject.SqlServer2008R2
{
    public class SqlServer2008R2Dialect : BaseDialect
    {
        static int BASE_PAGE_INDEX = 0;

        public SqlServer2008R2Dialect(SchemaConfig config = null)
            :base(config)
        {
        }

        #region ado.net object functions
        public override IDbConnection CreateConnection(string connectionString)
        {
            return new SqlConnection(connectionString);
        }

        public override IDbTransaction CreateTransaction(IDbConnection connection)
        {
            SqlConnection sqlConnection = (connection as SqlConnection);
            bool wasClosed = sqlConnection != null && sqlConnection.State == ConnectionState.Closed;
            if (wasClosed)
            {
                sqlConnection.Open();
            }
            return sqlConnection.BeginTransaction();
        }
        
        public override IDbCommand CreateCommand(IDbTransaction transaction, string sql)
        {
            SqlConnection sqlConnection = (transaction.Connection as SqlConnection);
            SqlTransaction sqlTransaction = (transaction as SqlTransaction);
            if (transaction == null)
            {
                return new SqlCommand(sql, sqlConnection);
            }
            else
            {
                return new SqlCommand(sql, sqlConnection, sqlTransaction);
            }
        }

        public override IDbCommand CreateCommand(IDbConnection connection, string sql)
        {
            SqlConnection sqlConnection = (connection as SqlConnection);
            return new SqlCommand(sql, sqlConnection);
        }

        public override IDbDataAdapter CreateAdapter(IDbConnection connection, string sql)
        {
            SqlConnection sqlConnection = (connection as SqlConnection);
            return new SqlDataAdapter(sql, sqlConnection);
        }

        public override IDbDataParameter CreateParameter()
        {
            return new SqlParameter();
        }
        #endregion

        public override object RetrieveKeyValue<T>(IDataReader reader, IDbCommand command)
        {
            Table table = SchemaHelper.CreateTable<T>();
            var keyColumnParameterName = NamingPattern.GetSaveParameterName(table.KeyColumn);
            var keyVal = (command as SqlCommand).Parameters[keyColumnParameterName].Value;
            return keyVal;
        }

        public override BaseSqlCreator GetSqlCreator(Table mainTable)
        {
            return new SqlCreatorForSqlServer2008R2(mainTable, this);
        }
    }
}
